package com.bii.gelapp;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import com.edmodo.cropper.CropImageView;
import com.edmodo.cropper.cropwindow.CropOverlayView;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class CropImageActivity extends ActionBarActivity {
	public static final int GALLERY_CHOOSER_INTENT = 1;
	
	//9 September
	String analysisorigin = "";
	
	Bitmap originalBmp;
	public static Bitmap activeBmp;
	public static CropImageView cropImageView;
	Button btProceed, btImage, btPrev, btCrop;
	ImageView croppedImageView;

	// Instance variables
	private static final int DEFAULT_ASPECT_RATIO_VALUES = 10;
	private static final String ASPECT_RATIO_X = "ASPECT_RATIO_X";
	private static final String ASPECT_RATIO_Y = "ASPECT_RATIO_Y";
	// Instance variables
    private int mAspectRatioX = DEFAULT_ASPECT_RATIO_VALUES;
    private int mAspectRatioY = DEFAULT_ASPECT_RATIO_VALUES;
    
    public String filepath;

	protected void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        bundle.putInt(ASPECT_RATIO_X, mAspectRatioX);
        bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY);
    }

    // Restores the state upon rotating the screen/restarting the activity
    @Override
    protected void onRestoreInstanceState(Bundle bundle) {
        super.onRestoreInstanceState(bundle);
        mAspectRatioX = bundle.getInt(ASPECT_RATIO_X);
        mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y);
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cropimageactivity);
		//Origin = getIntent().getExtras()
		if (getIntent().hasExtra("analysisorigin")) {
			analysisorigin = getIntent().getStringExtra("analysisorigin");
		}
		
		cropImageView = (CropImageView) findViewById(R.id.CropImageView);
		btImage = (Button) findViewById(R.id.btImage);
		btCrop = (Button) findViewById(R.id.btCrop);
		btProceed = (Button) findViewById(R.id.btProceed);

		btCrop.setEnabled(false);
		btProceed.setEnabled(false);
		croppedImageView = (ImageView) findViewById(R.id.croppedImageView);
		
		Log.d("tag1", "before cropImageView height: " + cropImageView.getHeight() + " cropImageView width: " + cropImageView.getWidth());
		

		btImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, GALLERY_CHOOSER_INTENT);
			}
		});

		btCrop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Bitmap croppedImage = cropImageView.getCroppedImage();

				croppedImageView.setImageBitmap(croppedImage);
				activeBmp = croppedImage;
			}

		});

		btProceed.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Display display = getWindowManager().getDefaultDisplay();
				Point size = new Point();
				display.getSize(size);
				int screenwidth = size.x;
				int screenheight = size.y;
				Log.d("tag1", "screenwidth: " + screenwidth + " screenheight: " + screenheight);
				
				if (activeBmp.getWidth() > activeBmp.getHeight()) {
					//if (img.getWidth() > screenwidth) {
					activeBmp = Bitmap
								.createScaledBitmap(activeBmp, screenwidth, ((screenwidth * activeBmp
										.getHeight()) / activeBmp.getWidth()),
										true);

					//}
				} else if(activeBmp.getHeight() > activeBmp.getWidth()) {
					//if (img.getHeight() > screenheight) {
					activeBmp = Bitmap
								.createScaledBitmap(activeBmp, ((screenheight * activeBmp
										.getWidth())/ activeBmp.getHeight()),
										screenheight, true);

					//}
				}
				else
				{
					activeBmp = Bitmap.createScaledBitmap(activeBmp, screenwidth,
							screenwidth, true);
				}

				try {
					InternalStorage.writeBitmap(CropImageActivity.this,
							"colorBmp", activeBmp);
					Intent goToNextActivity = new Intent(
							getApplicationContext(), BrightnessActivity3.class);
					goToNextActivity.putExtra("analysisorigin", analysisorigin);
					
					startActivity(goToNextActivity);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		// Setup handler for uncaught exceptions.
		Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
			@Override
			public void uncaughtException(Thread thread, Throwable e) {
				handleUncaughtException(thread, e);
			}
		});
		
		ImageView ivcropimage = (ImageView) cropImageView.getChildAt(0);

	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Check if the specified image exists.
		cropImageView.requestLayout();
		if (filepath != null) {
			if (!new File(filepath).exists()) {
				Toast.makeText(this, "Image does not exist.",
						Toast.LENGTH_SHORT).show();
			} else {
				// Display image in ImageView.
				Bitmap img = BitmapFactory.decodeFile(filepath);

				if (img.getWidth() < img.getHeight()) {
					Bitmap rotatedbmp = RotateBitmap(img, 90);
					img = rotatedbmp;
				} else {
					;
				}

				Log.d("tag1", "img dimensions w: " + img.getWidth()
						+ " h: " + img.getHeight());
				
				Display display = getWindowManager().getDefaultDisplay();
				Point size = new Point();
				display.getSize(size);
				int screenwidth = size.x;
				int screenheight = size.y;
				Log.d("tag1", "screenwidth: " + screenwidth + " screenheight: " + screenheight);
				
				if (img.getWidth() > img.getHeight()) {
					//if (img.getWidth() > screenwidth) {
						img = Bitmap
								.createScaledBitmap(img, screenwidth, ((screenwidth * img
										.getHeight()) / img.getWidth()),
										true);

					//}
				} else if(img.getHeight() > img.getWidth()) {
					//if (img.getHeight() > screenheight) {
						img = Bitmap
								.createScaledBitmap(img, ((screenheight * img
										.getWidth())/ img.getHeight()),
										screenheight, true);

					//}
				}
				else
				{
					img = Bitmap.createScaledBitmap(img, screenwidth,
							screenwidth, true);
				}
				
				int orientation = getResources().getConfiguration().orientation;
				if(orientation == Configuration.ORIENTATION_LANDSCAPE){
					img = Bitmap.createScaledBitmap(img, img.getWidth() - 200,
							img.getHeight() - 200, true);
				}

				activeBmp = img.copy(Bitmap.Config.ARGB_8888, true);
				
				Log.d("tag1", "img scaled dimensions w: " + img.getWidth()
						+ " h: " + img.getHeight());
				
				//cropImageView.getLayoutParams().height = screenheight;
				//LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
				//lp.setMargins(50, 0, 50, 0);
				//cropImageView.setLayoutParams(lp);
				cropImageView.getLayoutParams().height = activeBmp.getHeight();
				//cropImageView.getLayoutParams().width = screenwidth - 100;
				cropImageView.getLayoutParams().width = activeBmp.getWidth();
				cropImageView.setImageBitmap(activeBmp);
				
				croppedImageView.setImageBitmap(activeBmp);
				img.recycle();

				btCrop.setEnabled(true);
				btProceed.setEnabled(true);
			}
		}
	}
	
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == GALLERY_CHOOSER_INTENT) {
			// Get the filepath and display on imageview.
			
			filepath = getGalleryImagePath(data);
			// Check if the specified image exists.
			cropImageView.requestLayout();
			if (filepath != null) {
				if (!new File(filepath).exists()) {
					Toast.makeText(this, "Image does not exist.",
							Toast.LENGTH_SHORT).show();
				} else {
					// Display image in ImageView.
					Bitmap img = BitmapFactory.decodeFile(filepath);

					if (img.getWidth() < img.getHeight()) {
						Bitmap rotatedbmp = RotateBitmap(img, 90);
						img = rotatedbmp;
					} else {
						;
					}

					Log.d("tag1", "img dimensions w: " + img.getWidth()
							+ " h: " + img.getHeight());
					
					Display display = getWindowManager().getDefaultDisplay();
					Point size = new Point();
					display.getSize(size);
					int screenwidth = size.x;
					int screenheight = size.y;
					Log.d("tag1", "screenwidth: " + screenwidth + " screenheight: " + screenheight);
					
					if (img.getWidth() > img.getHeight()) {
						//if (img.getWidth() > screenwidth) {
							img = Bitmap
									.createScaledBitmap(img, screenwidth, ((screenwidth * img
											.getHeight()) / img.getWidth()),
											true);

						//}
					} else if(img.getHeight() > img.getWidth()) {
						//if (img.getHeight() > screenheight) {
							img = Bitmap
									.createScaledBitmap(img, ((screenheight * img
											.getWidth())/ img.getHeight()),
											screenheight, true);

						//}
					}
					else
					{
						img = Bitmap.createScaledBitmap(img, screenwidth,
								screenwidth, true);
					}
					activeBmp = null;
					activeBmp = img.copy(Bitmap.Config.ARGB_8888, true);
					
					Log.d("tag1", "img scaled dimensions w: " + img.getWidth()
							+ " h: " + img.getHeight());
					
					//cropImageView.getLayoutParams().height = screenheight;
					//LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
					//lp.setMargins(50, 0, 50, 0);
					//cropImageView.setLayoutParams(lp);
					cropImageView.getLayoutParams().height = activeBmp.getHeight();
					//cropImageView.getLayoutParams().width = screenwidth - 100;
					cropImageView.getLayoutParams().width = activeBmp.getWidth();
					cropImageView.setImageBitmap(activeBmp);
					
					croppedImageView.setImageBitmap(activeBmp);
					img.recycle();

					btCrop.setEnabled(true);
					btProceed.setEnabled(true);
					
					
					
				}
			}
		}
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus){
		Log.d("tag1", "after cropImageView height: " + cropImageView.getMeasuredHeight() + 
				" cropImageView width: " + cropImageView.getMeasuredWidth());
	}
	
	

	public String getGalleryImagePath(Intent data) {
		try {
			Uri imgUri = data.getData();
			String filePath = "";
			if (data.getType() == null) {
				// For getting images from default gallery app.
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(imgUri,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				filePath = cursor.getString(columnIndex);
				cursor.close();
			} else if (data.getType().equals("image/jpeg")
					|| data.getType().equals("image/png")) {
				filePath = imgUri.getPath();
			}
			return filePath;
		} catch (Exception e) {
			return null;
		}

	}
	
	/*
	//for opencv manager
	public BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
		@Override
		public void onManagerConnected(int status) {
			switch (status) {
			case LoaderCallbackInterface.SUCCESS:
				// DO YOUR WORK/STUFF HERE
				break;
			default:
				super.onManagerConnected(status);
				break;
			}
		}
	};

	// onresume is for the opencv
	@Override
	protected void onResume() {
		super.onResume();
		OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, this,
				mOpenCVCallBack);
	}
	*/

	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 100, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;
	}

	public void handleUncaughtException(Thread thread, Throwable e) {
		e.printStackTrace();

		System.exit(1); // kill off the crashed app
	}

	public static Bitmap RotateBitmap(Bitmap source, float angle) {
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
				source.getHeight(), matrix, true);
	}
}
